﻿const puppeteer = require('puppeteer')
var CONFIG = require('./config.js')
const ora = require('ora')
var spinner = ora('Loading unicorns')
const notifier = require('node-notifier')
const path = require('path')
let number = 0
var urlList = [],
    t,
    listType = 'Document',
    pagenumber = 0,
    pageUrl = {
        Document: 'DocumentKnowledge',
        Video: 'VideoKnowledge'
    }

const goFn = async () => {
    global.browser = await puppeteer.launch({
        defaultViewport: {
            width: 1400,
            height: 930
        },
        timeout: 0, //timeout here is 无限制
        args: ['--disable-bundled-ppapi-flash=true'],
        // devtools: true,
        // headless: false
        headless: true
    })
    global.page = CONFIG.PAGE;
    console.log(`当前登陆用户 ${CONFIG.USERNAME}`)
    spinner.text = `正在登陆`
    spinner.start()
    const login = await browser.newPage()
    await login.goto(CONFIG.LOGINURL)
    // await doLogin(login, config);
    await doLogin(login)

    // })
}
const goList = async () => {
    spinner.stop()
    spinner.text = `正在跳转至第${global.page}页`
    spinner.start()
    const resUrl = CONFIG.BRUSHONLINECLASSESLISTURL + `?t=${pageUrl[listType]}&ps=50&pi=` + global.page;
    await global.list.goto(
        resUrl
    )
    const useName = await global.list.$$eval('#divaccount > div.accountblick > span:nth-child(2)', elements => elements.map(el => el.innerText))
    if(useName == undefined || useName == null || useName.length <= 0){
        spinner.stopAndPersist({
            symbol: `❌`,
            text: `登录失败 用户名密码错误 或者需要输入验证码。如果需要输入验证码 请手动登录后重启脚本`
        })
        return
    }
    await doList(list)
}
const doLogin = async (login, config) => {
    const loginForm = await login.$('#dvUserNameLoginPanel')
    const usernameLo =  await loginForm.$('#txtUserName2');
    await usernameLo.type(CONFIG.USERNAME, {delay: 20});
    const passwordLo =  await loginForm.$('#txtPassword2');
    await passwordLo.type(CONFIG.PASSWORD, {delay: 20});
    await loginForm.$eval('#chkloginpass', (loginBtn) => loginBtn.click())
    await loginForm.$eval('#btnLogin2', (loginBtn) => loginBtn.click())
    setTimeout(async () => {
        global.list = await global.browser.newPage()
        await goList()
    }, 2000)
}
const doList = async (list) => {
    const listDiv = await list.$('.el-kng-img-list')
    if (!listDiv) return
    pagenumber = await list.evaluate(() => {
        let list = [...document.querySelectorAll('.pagenumber')]
        return list[list.length - 1].innerText
    })
    urlList = await list.evaluate(() => {
        let list = [...document.querySelectorAll('.el-placehold-body')]
        return list.map((v) => {
            return `http://edu.piesat.cn` + v.getAttribute('onclick').split("'")[1]
        })
    })
    // await getDocumentPage(urlList)

    await eval(`get${listType}Page(urlList)`)
    // await list.close();
}
const getDocumentPage = async (list) => {
    try {
        t && clearTimeout(t)
        if (list.length == 0) {
            goList()
            spinner.stop()
            return
        }
        let datePage = await global.browser.newPage()
        let url = list.shift()
        if (!url || typeof url != 'string') {
            await datePage.close()
            await getDocumentPage(list)
            return
        }
        await datePage.goto(url, {
            timeout: 60000 //timeout here is 60 seconds
        })
        await global.list.reload({
            timeout: 60000 //timeout here is 60 seconds
        })
        const spanTexts = await global.list.$$eval('#UserDayPoint1', elements => elements.map(el => el.innerText))
        if(spanTexts != undefined && spanTexts >= CONFIG.TARGETSCORE){
            spinner.stopAndPersist({
                symbol: `√`,
                text: `以达到当日积分目标${CONFIG.TARGETSCORE}分 结束刷课!`
            })
            return
        }
        else {
            spinner.text = `正在阅读第${global.page}页,共${pagenumber}页,已读${number}篇文档 今日已学习积分：${spanTexts}`
        }
        spinner.start()
        number++
        let flag = await datePage.evaluate(() => {
            return $('#ScheduleText').text() == '100%'
        })
        if (flag) {
            await datePage.close()
            getDocumentPage(list)
            return
        } else {
            await datePage.evaluate(() => {
                setInterval(async () => {
                    submitStudy()
                    SyncSchedule()
                }, 1000)
            })
            t = await setTimeout(async () => {
                await datePage.close()
                await getDocumentPage(list)
            }, 16000)
        }
    } catch (err) {
        console.log(err)
    }
}
const getVideoPage = async (list) => {
    try {
        t && clearInterval(t)
        if (list.length == 0) {
            await goList()
        }
        let url = list.shift()
        if (!url || typeof url != 'string') {
            await datePage.close()
            await getVideoPage(list)
            return
        }
        let datePage = await global.browser.newPage()
        await datePage.goto(url, {
            timeout: 60000 //timeout here is 60 seconds
        })
        t = setInterval(async () => {
            let flag = await datePage.evaluate(() => {
                return $('#ScheduleText').text() == '100%'
            })
            if (flag) {
                await datePage.close()
                // await setTimeout(async () => {
                clearInterval(t)
                await getVideoPage(list)
                // });
                return
            } else {
                await datePage.evaluate(() => {
                    setInterval(() => {
                        let time = $('.jw-text-duration').text().split(':')
                        let videoTime = 0
                        let timeInterval = [1, 60, 3600]
                        for (let index = time.length - 1; index > 0; index--) {
                            videoTime += time[index] * timeInterval[index]
                        }
                        $('#hidViewSchedule').val(videoTime + '')
                        submitStudy()
                        SyncSchedule()
                    }, 1000)
                })
            }
        }, 1000)
    } catch (err) {
    }
}

const notifierFn = ({title, message}) => {
    notifier.notify(
        {
            title: title,
            message: message,
            icon: path.join(__dirname, 'logo.png'), // Absolute path (doesn't work on balloons)
            sound: true, // Only Notification Center or Windows Toasters
            wait: true // Wait with callback, until user action is taken against notification
        },
        function (err, response) {
            // Response is response from notification
            if (err) {
                // errLog(err)
                // errLog(response)
            }
        }
    )
}
module.exports = goFn
